package guilddao

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"xr-game-server/core/cache"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/constants/db"
	"xr-game-server/core/lambda"
	"xr-game-server/entity"
)

var memberCache *cache.CacheMgr

func initMember() {
	memberCache = cache.NewCacheMgr()
}

// GetGuildMembers 获取公会所有成员
func GetGuildMembers(guildId uint64) []*entity.GuildMember {
	// 先从缓存获取
	cacheData := memberCache.GetData(guildId, func(ctx context.Context) (value interface{}, err error) {
		members := make([]*entity.GuildMember, common.Zero)
		g.Model(string(entity.TbGuildMember)).Unscoped().Where(g.Map{
			string(entity.GuildMemberGuildId): guildId,
			string(db.IsDeletedName):          false,
		}).OrderAsc(string(db.UpdatedAtName)).Scan(&members)
		return members, nil
	})
	return cacheData.([]*entity.GuildMember)
}

func GetMemberByRoleId(guildId uint64, roleId uint64) *entity.GuildMember {
	cacheData := GetGuildMembers(guildId)
	ret, _ := lambda.Find(cacheData, func(item *entity.GuildMember) bool {
		return item.RoleId == roleId
	})
	return ret
}

func DelMember(guildId uint64, roleId uint64) {
	cacheData := GetGuildMembers(guildId)
	ret := lambda.Filter(cacheData, func(item *entity.GuildMember) bool {
		return item.RoleId != roleId
	})
	memberCache.FlushCache(guildId, ret)
}

func AddMember(member *entity.GuildMember) {
	cacheData := GetGuildMembers(member.GuildId)
	cacheData = append(cacheData, member)
	memberCache.FlushCache(member.GuildId, cacheData)
}
